package com.weacar.springboot.logback.access;

import ch.qos.logback.access.tomcat.LogbackValve;
import org.apache.catalina.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;

/**
 * @author Fong
 * @since 1.0.0
 */
@Configuration
public class LogbackAccessConfiguration {
    private static Logger LOG = LoggerFactory.getLogger(LogbackAccessConfiguration.class);

    @Bean
    @ConditionalOnWebApplication
    public EmbeddedServletContainerCustomizer containerCustomizer(
            final @Value("${logback.access.config.path:classpath:logback-access.xml}") String path)
            throws FileNotFoundException {

        final File file;
        String sysConfigPath = System.getProperty("logback.access.config.path");
        if (sysConfigPath != null) {
            file = ResourceUtils.getFile(sysConfigPath);
        } else {
            file = ResourceUtils.getFile(path);
        }


        return new EmbeddedServletContainerCustomizer() {

            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                if (container instanceof TomcatEmbeddedServletContainerFactory) {
                    ((TomcatEmbeddedServletContainerFactory) container)
                            .addContextCustomizers(new TomcatContextCustomizer() {

                                @Override
                                public void customize(Context context) {
                                    LogbackValve logbackValve = new LogbackValve();
                                    logbackValve.setFilename(file.getAbsolutePath());
                                    context.getPipeline().addValve(logbackValve);
                                }

                            });
                    LOG.info("Logback access config in the embedded tomcat, logback-access.xml --> " + file.getAbsolutePath());
                }
            }
        };

    }

}